import time

from selenium import webdriver
from selenium.webdriver.common.by import By
class juejin():
    def __init__(self):
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.get('https://juejin.cn/')

    def splid(self, height):
        self.driver.execute_script(
            f'window.scrollTo(0, {height});'
        )

    def parse_data(self):
        lis= self.driver.find_elements(By.XPATH, value='//div[@name="entry-list"]/li')
        print(len(lis))
        for li in lis:
            time.sleep(1)
            li.find_element(By.XPATH,value='./div/div/div/div[1]/a').click()
            self.driver.switch_to.window(self.driver.window_handles[1])
            title = self.driver.find_element(By.CLASS_NAME, value="article-title").text
            contents = self.driver.find_elements(By.XPATH, value='//div[@id="article-root"]/p')
            s = ''
            for content in contents:
                s += content.text+'\n'
            print(s)
            self.driver.close()
            self.driver.switch_to.window(self.driver.window_handles[0])
            self.save_data(title, s)

    def save_data(self, title, s):
        with open(f'掘金/{title}.txt','w',encoding='utf-8')as f:
            f.write(s)


    def main(self):
        height = self.driver.get_window_size()['height']
        print(height)
        page = 1
        while page <= 5:

            self.splid(height)
            height = height + height
            page += 1
            time.sleep(2)
        self.parse_data()

jue = juejin()
jue.main()